package com.example.at_auth_plugin
import android.graphics.Color
import io.flutter.embedding.engine.plugins.activity.ActivityAware
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding
import android.app.Activity
import com.mobile.auth.gatewayauth.AuthUIConfig
import com.mobile.auth.gatewayauth.PhoneNumberAuthHelper
import com.mobile.auth.gatewayauth.TokenResultListener
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler


class AtAuthPlugin : FlutterPlugin, MethodCallHandler, ActivityAware {

  private lateinit var channel: MethodChannel
  private lateinit var activity: Activity
  private lateinit var mAuthHelper: PhoneNumberAuthHelper

  override fun onAttachedToEngine(binding: FlutterPlugin.FlutterPluginBinding) {
    channel = MethodChannel(binding.binaryMessenger, "at_auth_plugin")
    channel.setMethodCallHandler(this)
  }

  override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
    channel.setMethodCallHandler(null)
  }

  override fun onAttachedToActivity(binding: ActivityPluginBinding) {
    activity = binding.activity

    val mTokenResultListener = object : TokenResultListener {
      override fun onTokenSuccess(s: String) {
        // 处理成功
        channel.invokeMethod("onTokenSuccess", s)
      }

      override fun onTokenFailed(s: String) {
        channel.invokeMethod("onTokenFailed", s)
        // 处理失败
      }
    }

    mAuthHelper = PhoneNumberAuthHelper.getInstance(activity, mTokenResultListener)
  }

  override fun onDetachedFromActivity() {
    //activity = null
  }

  override fun onReattachedToActivityForConfigChanges(binding: ActivityPluginBinding) {
    onAttachedToActivity(binding)
  }

  override fun onDetachedFromActivityForConfigChanges() {
    onDetachedFromActivity()
  }

  override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
    when (call.method) {
      "setAuthSDKInfo" -> {
        handleSetAuthSDKInfo(call, result)
      }
      "setAuthUIConfig" -> {
        handleSetAuthUIConfig(call, result)
      }
      "getLoginToken" -> {
        handleGetLoginToken(call, result)
      }
      "getVersion" -> {
        handleGetVersion(call, result)
      }
      else -> result.notImplemented()
    }
  }

  private fun handleSetAuthSDKInfo(call: MethodCall, result: MethodChannel.Result) {
    val args = call.arguments as? Map<String, Any>
    val appSecret = args?.get("appSecret") as? String
    if (appSecret.isNullOrBlank()) {
      result.error(
        "INVALID_ARGUMENT", // errorCode，可用于 Dart 区分错误类型
        "appSecret is required", // message，错误描述
        null // details，可选，附加信息
      )
      return
    }
    try {
      mAuthHelper.setAuthSDKInfo(appSecret)
     result.success(mapOf("result" to "success")) // 正常返回成功
    } catch (e: Exception) {
      result.error("ERROR", e.localizedMessage, null)
    }
  }

  private fun  handleGetLoginToken(call: MethodCall, result: MethodChannel.Result) {
    val args = call.arguments as? Map<String, Any>
    val timeOut = args?.get("timeOut") as? Int ?: 5000

    try {

     var mTokenResultListener = object : TokenResultListener {
        override fun onTokenSuccess(s: String) {
          result.success(mapOf("success" to s)) // 正常返回成功
        }

        override fun onTokenFailed(s: String) {
          //此处可进行token获取失败及退出授权页的业务处理
          result.error("ERROR", s, null)
        }
      }
      
      mAuthHelper.setAuthListener(mTokenResultListener)
      mAuthHelper.getLoginToken(activity, timeOut)
      result.success(mapOf("result" to "success"))  // 正常返回成功
    } catch (e: Exception) {
      result.error("ERROR", e.localizedMessage, null)
    }
  }

  private fun handleSetAuthUIConfig(call: MethodCall, result: MethodChannel.Result) {
    //
    mAuthHelper.setAuthUIConfig(
      AuthUIConfig.Builder()
        .setAppPrivacyOne("《自定义隐私协议》", "https://www.baidu.com")
        .setAppPrivacyTwo(
          "《自定义隐私协议》2",
          "https://baijiahao.baidu.com/s?id=1693920988135022454&wfr=spider&for=pc"
        )
        .setAppPrivacyThree(
          "《自定义隐私协议》3",
          "http://www.npc.gov.cn/zgrdw/npc/cwhhy/13jcwh/node_35014.htm"
        )
        .setAppPrivacyColor(Color.GRAY, Color.parseColor("#002E00"))
        .setPrivacyConectTexts(arrayOf<String>(",", "", "和"))
        .setPrivacyOperatorIndex(2)
        .setPrivacyState(false) //.setCheckboxHidden(true)
        .setNavHidden(true)
        .setSwitchAccHidden(true)
        .setNavReturnHidden(true)
        .setDialogBottom(false) //自定义协议页跳转协议，需要在清单文件配置自定义intent-filter，不需要自定义协议页，则请不要配置ProtocolAction
        .setProtocolAction("com.aliqin.mytel.protocolWeb")
        //.setPackageName(mPackageName)
        .setNavColor(Color.TRANSPARENT)
        .setWebNavColor(Color.BLUE)

        .setLogoOffsetY(0)
        .setLogoWidth(42)
        .setLogoHeight(42)
        .setLogoImgPath("mytel_app_launcher")

       // .setNumFieldOffsetY(unit + 10) //设置字体大小，以Dp为单位，不同于Sp，不会随着系统字体变化而变化
        .setNumberSizeDp(17)

        //.setLogBtnWidth(dialogWidth - 30)
        .setLogBtnMarginLeftAndRight(15)
        //.setLogBtnHeight(logBtnHeight)
        .setLogBtnTextSizeDp(16)
        .setLogBtnBackgroundPath("login_btn_bg")

        //.setLogBtnOffsetY(unit * 4)
        .setSloganText("为了您的账号安全，请先绑定手机号")
        //.setSloganOffsetY(unit * 3)
        .setSloganTextSizeDp(11)

        .setPageBackgroundPath("dialog_page_background")

        .setAuthPageActIn("in_activity", "out_activity")
        .setAuthPageActOut("in_activity", "out_activity")
        .setVendorPrivacyPrefix("《")
        .setVendorPrivacySuffix("》")
        //.setDialogWidth(dialogWidth)
        //.setDialogHeight(dialogHeight)
        //.setScreenOrientation(authPageOrientation)
        .create()
    )
  }

  private fun handleGetVersion(call: MethodCall, result: MethodChannel.Result) {
      result.success("unKnown")
  }


}
